package cc.rengu.redp.base.authentication;

import cc.rengu.redp.common.properties.RedpProperties;
import cc.rengu.redp.common.utils.IPUtil;
import cc.rengu.redp.common.utils.RegexUtil;
import cc.rengu.redp.common.utils.SpringContextUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class JWTFilter extends BasicHttpAuthenticationFilter {

    private static final String TOKEN = "Authentication";

    private AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        RedpProperties redpProperties = SpringContextUtil.getBean(RedpProperties.class);
        String[] anonUrl = StringUtils.splitByWholeSeparatorPreserveAllTokens(redpProperties.getShiro().getAnonUrl(), StringPool.COMMA);

        boolean match = false;
        for (String u : anonUrl) {
            if (pathMatcher.match(u, httpServletRequest.getRequestURI())) {
                match = true;
            }
        }
        if (match) {
            return true;
        }
        if (isLoginAttempt(request, response)) {
            return executeLogin(request, response);
        }
        return false;
    }

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader(TOKEN);
        return token != null;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String token = httpServletRequest.getHeader(TOKEN);
        JWTToken jwtToken = new JWTToken(UpmpJWTUtil.decryptToken(token));
        try {
            getSubject(request, response).login(jwtToken);
            // 用户消息自动轮询不算用户有效操作
            String requestUri = ((HttpServletRequest) request).getRequestURI();
            if (UpmpJWTRefresh.USER_MSG_REFRESH.booleanValue() == false && requestUri.startsWith("/admin/userMessage/getUnreadMessageCount")) {
                return true;
            }

            // 验证通过后，进入token更新程序
            JWTTokenInfo updatedToken = UpmpJWTRefresh.getNewToken(jwtToken.getToken(), token, IPUtil.getIpAddr(httpServletRequest));
            if (updatedToken != null) {
                httpServletResponse.setHeader(UpmpJWTRefresh.TOKEN_UPDATE, updatedToken.getToken());
                httpServletResponse.setHeader(UpmpJWTRefresh.TOKEN_EXP_UPDATE, updatedToken.getExpireAt());
                httpServletResponse.setHeader("Access-Control-Expose-Headers", UpmpJWTRefresh.TOKEN_UPDATE + "," + UpmpJWTRefresh.TOKEN_EXP_UPDATE);
            }
            return true;
        } catch (Exception e) {
            log.warn(e.getMessage());
            return false;
        }
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String origin = httpServletRequest.getHeader("Origin");
        if (!RegexUtil.isHttp(origin)) return false;
        httpServletResponse.setHeader("Access-control-Allow-Origin", origin);
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");

        String ctlReqHeaders = httpServletRequest.getHeader("Access-Control-Request-Headers");
        if (StringUtils.isNotBlank(ctlReqHeaders)) {
            if (ctlReqHeaders.equalsIgnoreCase(TOKEN)) {
                httpServletResponse.setHeader("Access-Control-Allow-Headers", ctlReqHeaders);
            }else {
                return false;
            }
        }
        // 跨域时会首先发送一个 option请求，这里我们给 option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    @Override
    protected boolean sendChallenge(ServletRequest request, ServletResponse response) {
        log.debug("Authentication required: sending 401 Authentication challenge response.");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        log.info("req.getRequestURI()-----> {}",httpServletRequest.getRequestURI());
        log.info("req.getRequestURL()-----> {}",httpServletRequest.getRequestURL());
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpResponse.setCharacterEncoding("utf-8");
        httpResponse.setContentType("application/json; charset=utf-8");
        final String message = "未认证，请在前端系统进行认证";
        try (PrintWriter out = httpResponse.getWriter()) {
            String responseJson = "{\"message\":\"" + message + "\"}";
            out.print(responseJson);
        } catch (IOException e) {
            log.error("sendChallenge error：", e);
        }
        return false;
    }
}
